import * as THREE from "three";
import { Canvas } from "@react-three/fiber";
import { Suspense, useMemo } from "react";
import { Physics } from "@react-three/rapier";
import {
  AdaptiveDpr,
  Environment,
  KeyboardControls,
  OrbitControls,
  Preload,
  Sky,
} from "@react-three/drei";
import Ground from "./ground";
import Ambiance from "./ambiance";
import { Player, PovPlayer } from "./player";
import { useControls, Leva } from "leva";
import { Perf } from "r3f-perf";
import { DEBUG, POV } from "@/config";

function Models() {
  const autoRotate = false;
  const actions = [
    { name: "forward", keys: ["ArrowUp", "w", "W"] },
    { name: "backward", keys: ["ArrowDown", "s", "S"] },
    { name: "left", keys: ["ArrowLeft", "a", "A"] },
    { name: "right", keys: ["ArrowRight", "d", "D"] },
    { name: "jump", keys: ["Space"] },
  ];
  // 控制器
  const controlConfig = useMemo(
    () => ({
      reverseOrbit: false,
      enableZoom: true,
      enableRotate: true,
      autoRotate: autoRotate,
      autoRotateSpeed: 0.5,
      enableDamping: true,
      dampingFactor: 0.2,
      rotateSpeed: 0.5,
    }),
    [autoRotate]
  );

  // 参数调试面板
  const { controlType, debug, showCollider, showPerf, showHelper } =
    useControls({
      controlType: { value: "default", options: ["default", "pov"] },
      debug: {
        value: false,
        options: [false, true],
      },
      showCollider: {
        value: false,
        options: [false, true],
      },
      showPerf: {
        value: false,
        options: [false, true],
      },
      showHelper: {
        value: false,
        options: [false, true],
      },
    });

  return (
    <Canvas
      style={{ width: "100%", height: "100%" }}
      camera={{ fov: 60, position: [3, 1, 3] }}
      onCreated={({ gl }) => {
        gl.toneMapping = THREE.ReinhardToneMapping;
        gl.setClearColor(new THREE.Color("#020209"));
      }}
    >
      <Suspense fallback={null}>
        <KeyboardControls map={actions}>
          <Physics debug={showCollider || debug}>
            {controlType == "pov" || POV ? <PovPlayer /> : <Player />}
            <Ground />
          </Physics>

          <OrbitControls {...controlConfig} makeDefault />
        </KeyboardControls>

        <ambientLight intensity={1} />
        <Sky sunPosition={[100, 20, 100]} distance={1000} />
        <directionalLight position={[100, 100, 100]} intensity={1.5} />
        <Environment files={"./textures/city_env.hdr"} />

        {(showPerf || debug) && <Perf position="top-left" />}
        <Ambiance debug={showHelper || debug} />
        {(showHelper || debug) && <axesHelper args={[500]} />}
        {/* Leva 面板 */}
        {!DEBUG && <Leva hidden={!DEBUG} />}
      </Suspense>

      {/* 预加载可见对象 */}
      <Preload />
      {/* 允许暂时降低视觉质量以换取更多性能，例如当相机移动时 */}
      <AdaptiveDpr pixelated />
    </Canvas>
  );
}

export default Models;
